<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="110"
          class="search-form"
          @submit.native.prevent
        >
          <Form-item label="实践实训基地类型" prop="type">
            <Select
              v-model="searchForm.type"
              placeholder="请选择实践实训基地类型"
              clearable
              style="width: 200px"
            >
              <Option v-for="(item, index) in typeList" :key="index" :value="item.id">{{
                item.name
              }}</Option>
            </Select>
          </Form-item>
          <Form-item label="实践实训基地名称" prop="name">
            <Input
              type="text"
              v-model="searchForm.name"
              placeholder="请输入实践实训基地名称"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="状态" prop="status">
            <Select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <Option
                v-for="(item, index) in statusList"
                :key="index"
                :value="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
            >搜索</Button
          >
        </Form>
      </Row>
      <Row class="operation padding-row">
        <Button @click="addBase" type="error">添加</Button>
        <Button @click="batchAppointment" type="error">批量设置预约时段</Button>
        <Button @click="batchDel">批量删除</Button>
      </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        sortable="custom"
        class="mt_10"
        :data="data"
        ref="table"
        @on-selection-change="changeSelect"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.page"
          :total="total"
          :page-size="searchForm.rows"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>
    <!-- 预约时段设置模态框 -->
    <Modal v-model="editFlag" title="预约时段设置" :width="900">
      <Form ref="editForm" :model="editForm" :rules="rules" :label-width="100">
        <FormItem label="开放未来" prop="workFutureDays" type="number" style="width: 50%">
          <Input
            v-model="editForm.workFutureDays"
            maxlength="4"
            placeholder="请输入大于0的整数"
          />
        </FormItem>
        <FormItem label="开放日期" prop="weekDays" required style="width: 100%">
          <span v-for="(i, k) in dateRange" :key="k">
            <span style="padding: 0 10px">{{ i.label }}</span>
            <i-switch
              size="large"
              @on-change="dayChange"
              true-color="#13ce66"
              :true-value="1"
              :false-value="0"
              v-model="i.value"
            >
              <span slot="open">开放</span>
              <span slot="close">关闭</span>
            </i-switch>
          </span>
        </FormItem>
        <FormItem label="开放时段" prop="time" style="width: 50%">
          <div v-for="(i, k) in times" :key="k">
            <TimePicker
              type="timerange"
              v-model="i.value"
              @on-change="timeChange"
              format="HH:mm"
              placement="bottom-end"
              placeholder="请选择时段"
            ></TimePicker>
            <Icon
              type="md-add"
              v-if="k == times.length - 1"
              style="padding: 10px"
              @click="handleAdd"
            />
            <Icon type="md-remove" style="padding: 10px" @click="handleDel(k)" />
          </div>
          <Icon
            type="md-add"
            v-if="!times.length"
            style="padding: 10px"
            @click="handleAdd"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="editFlag = false">取消</Button>
        <Button type="primary" @click="submitForm">提交</Button>
      </div>
    </Modal>
    <Modal v-model="detailFlag" title="实践实训基地详情" footer-hide width="65%">
      <div v-if="detailFlag" class="modal-info">
        <Row :gutter="20">
          <Col span="4" style="text-align: right">基地所属单位</Col>
          <Col span="20">{{ editRow.deptStr }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">实践实训基地名称</Col>
          <Col span="20">{{ editRow.name }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">实践实训基地类型</Col>
          <Col span="20">{{ editRow.trainingTypeStr }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">容纳人数</Col>
          <Col span="20">{{ editRow.capacity }}人</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">基地地址</Col>
          <Col span="20">{{ editRow.siteAddress }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">基地电话</Col>
          <Col span="20">{{ editRow.telephone }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">收费标准</Col>
          <Col span="20">{{ editRow.unitPrice }} 元 / 小时</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">基地封面</Col>
          <Col span="20">
            <img
              v-if="editRow.trainingBaseCover"
              :src="editRow.trainingBaseCover"
              style="height: 150px; margin: 0 20px 20px 0"
            />
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">基地照片</Col>
          <Col span="20">
            <img
              v-for="(i, k) in editRow.picList"
              :key="k"
              :src="i"
              style="height: 150px; margin: 0 20px 20px 0"
            />
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">实践实训基地介绍</Col>
          <Col span="20">
            <div class="box-border" v-html="editRow.trainingBaseDetail"></div
          ></Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Train from "@/api/trainbase.js";

export default {
  name: "train-base",
  data() {
    return {
      loading: false, // 加载状态
      searchForm: {
        // 请求参数
        page: 1,
        rows: 10,
        type: null, //基地类型
        name: null, //基地名称
        status: null, //基地状态
      },
      selectList: [], // 多选数据
      typeList: [], // 基地类型列表
      statusList: [
        // 基地状态
        { value: 0, label: "开放" },
        { value: 1, label: "关闭" },
      ],
      editFlag: false, // 预约时段设置弹窗
      editForm: {
        // 预约时段表单
        id: "",
        workFutureDays: "", //开放天数
        weekDays: "", //开放日期
        siteTimes: [], //开放时段
      },
      dateRange: [
        { value: 1, label: "周一" },
        { value: 1, label: "周二" },
        { value: 1, label: "周三" },
        { value: 1, label: "周四" },
        { value: 1, label: "周五" },
        { value: 1, label: "周六" },
        { value: 1, label: "周日" },
      ],
      times: [{ value: "", id: "" }],
      rules: {
        // 验证规则
        workFutureDays: [
          { required: true, message: "请输入开放天数" },
          {
            pattern: /^[0-9]*[1-9][0-9]*$/,
            message: "只能输入大于0的整数",
            trigger: "blur",
          },
        ],
        siteTimes: [{ required: true, message: "请选择开放时段" }],
      },
      columns: [
        // 表头
        { type: "selection", width: 60, align: "center" },
        { title: "序号", minWidth: 100, type: "index" },
        {
          title: "实践实训基地名称",
          minWidth: 300,
          tooltip: true,
          render: (h, params) => {
            let func = [];
            if (params.row.trainingBaseCover) {
              func.push(
                h("img", {
                  attrs: { src: params.row.trainingBaseCover },
                  style: { width: "100px" },
                })
              );
            }
            if (params.row.name) {
              func.push(h("span", { style: { margin: "auto 10px" } }, params.row.name));
            }
            return h("div", { style: { display: "flex" } }, func);
          },
        },
        {
          title: "实践实训基地类型",
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            let label = "";
            this.typeList.forEach((i) => {
              if (i.id == params.row.type) label = i.name;
            });
            return h("span", {}, label);
          },
        },
        { title: "容纳人数", key: "capacity", minWidth: 120, tooltip: true },
        { title: "基地位置", key: "siteAddress", minWidth: 120, tooltip: true },
        {
          title: "收费标准",
          minWidth: 120,
          tooltip: true,
          render: (h, params) => {
            let label = "免费";
            if (params.row.isCharge == 1) label = params.row.unitPrice + "元/小时";
            return h("span", {}, label);
          },
        },
        {
          title: "状态",
          minWidth: 120,
          render: (h, params) => {
            return h("div", [
              h("div", {
                style: {
                  display: "inline-block",
                  width: "8px",
                  height: "8px",
                  backgroundColor: params.row.status == 0 ? "#68CABE" : "#FF5C58",
                  marginRight: "6px",
                  borderRadius: "50%",
                },
              }),
              h("span", {}, params.row.status == 0 ? "开放" : "关闭"),
            ]);
          },
        },
        {
          title: "操作",
          align: "center",
          width: 300,
          fixed: "right",
          render: (h, params) => {
            let label = params.row.status == 1 ? "开放" : "关闭";
            return h("div", { style: { display: "flex", justifyContent: "center" } }, [
              this.btnDom(h, "warning", "编辑", "editPerm", params),
              this.btnDom(h, "success", "预约时段", "appointment", params),
              this.btnDom(h, "info", "查看", "handleView", params, true),
              this.btnDom(h, null, label, "handleStatus", params),
              this.btnDom(h, "error", "删除", "handleDelRow", params),
            ]);
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      editRow: {}, //单选数据
      detailFlag: false, //详情弹窗
    };
  },
  methods: {
    // 分页 改变页码
    changePage(v) {
      this.searchForm.page = v;
      this.getData();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.searchForm.rows = v;
      this.searchForm.page = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.page = 1;
      this.searchForm.rows = 10;
      this.getData();
    },
    //多选
    changeSelect(e) {
      this.selectList = e;
    },
    // 按钮
    btnDom(h, type = null, label = "", method, params, ghost = false) {
      return h(
        "Button",
        {
          props: { type, size: "small", ghost },
          style: { marginRight: "5px" },
          on: {
            click: () => {
              this[method](params.row);
            },
          },
        },
        label
      );
    },
    // 新增
    addBase() {
      this.$router.push({
        name: "base-form",
        query: { id: null },
      });
    },
    //修改
    editPerm(v) {
      this.$router.push({
        name: "base-form",
        query: { id: v.id },
      });
    },
    // 查看
    handleView(v) {
      this.editRow = v;
      this.detailFlag = true;
    },
    // 设置预约时段
    appointment(row) {
      this.editFlag = true;
      this.editRow = row;
      this.editForm = {
        id: row.id,
        workFutureDays: row.workFutureDays,
        weekDays: row.weekDays,
        siteTimes: row.siteTimes,
      };
      // 回显时段
      this.times = row.siteTimes.map((i) => {
        return {
          value: i.timeSlot.split("~"),
          id: i.id,
        };
      });
      // 回显开放日期
      let weeks = row.weekDays.split("");
      this.dateRange.forEach((i, k) => {
        i.value = parseInt(weeks[k]);
      });

      this.$refs.table.selectAll(false);
    },
    // 新增开放时段
    handleAdd() {
      this.times.push({ value: "", id: "" });
    },
    // 删除开放时段
    handleDel(index) {
      this.times.splice(index, 1);
      this.timeChange();
    },
    // 批量预约时段
    batchAppointment() {
      if (this.selectList.length) {
        this.editFlag = true;
        this.editRow = {};
        this.editForm = {
          id: "",
          workFutureDays: "",
          weekDays: "",
          siteTimes: [],
        };
        this.dayChange();
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 批量删除
    batchDel() {
      if (this.selectList.length) {
        this.$Modal.confirm({
          title: "确认删除",
          content: "<p>您确认要删除所选的" + this.selectList.length + "条数据？</p>",
          onOk: () => {
            let ids = this.selectList
              .map((i) => {
                return i.id;
              })
              .join(",");
            API_Train.delTrainBase({ ids }).then((res) => {
              if (res.success) {
                this.$Message.success("删除成功");
                this.getData();
              }
            });
          },
        });
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 删除
    handleDelRow(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "<p>您确认要删除本条数据？</p>",
        onOk: () => {
          API_Train.delTrainBase({ ids: v.id }).then((res) => {
            if (res.success) {
              this.$Message.success("删除成功");
              this.getData();
            }
          });
        },
      });
    },
    // 选择开放日期
    dayChange() {
      this.editForm.weekDays = this.dateRange
        .map((i) => {
          return i.value;
        })
        .join("");
    },
    // 选择开放时段
    timeChange() {
      let temp = this.times.filter((i) => i.value);
      this.editForm.siteTimes = temp.map((i) => {
        return { timeSlot: i.value.join("~"), id: i.id };
      });
    },
    // 提交设置
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.selectList.length) {
            this.editForm.id = this.selectList
              .map((i) => {
                return i.id;
              })
              .join(",");
            // 批量提交
          } else {
            // 单个提交
            this.editForm.id = this.editRow.id;
          }
          API_Train.postTrainBase(this.editForm).then((res) => {
            if (res.success) {
              this.$Message.success("修改成功");
              this.editFlag = false;
              this.getData();
            }
          });
        }
      });
    },
    //查询基地列表
    getData() {
      this.loading = true;
      API_Train.postTrainBasePage(this.searchForm)
        .then((res) => {
          if (res.success) {
            this.data = res.result.records;
            this.total = parseInt(res.result.total);
            this.data.forEach((i) => {
              i.picList = i.picUrls.split(",");
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 禁-开放状态
    handleStatus(v) {
      let params = {
        id: v.id,
        status: v.status == 1 ? 0 : 1,
      };
      this.$Modal.confirm({
        title: "确认" + (v.status == 1 ? "开放" : "关闭"),
        content:
          "<p>您确认要" + (v.status == 1 ? "开放" : "关闭") + "基地" + v.name + "？</p>",
        onOk: () => {
          API_Train.postTrainBase(params).then((res) => {
            if (res.success) {
              this.$Message.success((v.status == 1 ? "开放" : "关闭") + "成功");
              this.getData();
            }
          });
        },
      });
    },
    // 获取实训基地类型
    getBaseType() {
      API_Train.getTrainBaseType().then((res) => {
        if (res.success) {
          this.typeList = res.result;
        }
      });
    },
  },
  mounted() {
    this.getData();
    this.getBaseType();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ivu-table-wrapper {
  width: 100%;
}
::v-deep .ivu-card {
  width: 100%;
}
.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.modal-info {
  height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
  .ivu-row {
    min-height: 60px;
    height: auto;
  }
  .box-border {
    min-height: 60px;
    width: 80%;
    height: auto;
  }
}
</style>
